/*
 * @lc app=leetcode.cn id=529 lang=cpp
 *
 * [529] 扫雷游戏
 */

// @lc code=start
class Solution
{
public:
    struct Cell
    {
        int x, y;
    };

    int dirs[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};

    int getMines(vector<vector<char>> &board, int x, int y)
    {
        int mines = 0;
        for (int i = 0; i < 8; i++)
        {
            int nx = x + dirs[i][0];
            int ny = y + dirs[i][1];
            if (nx >= 0 && nx < board.size() && ny >= 0 && ny < board[0].size())
            {
                if (board[nx][ny] == 'M')
                    mines++;
            }
        }
        return mines;
    }

    vector<vector<char>> updateBoard(vector<vector<char>> &board, vector<int> &click)
    {
        if (board[click[0]][click[1]] == 'M')
        {
            board[click[0]][click[1]] = 'X';
            return board;
        }
        int m = board.size(), n = board[0].size();
        queue<Cell> q;
        q.push({click[0], click[1]});
        board[click[0]][click[1]] = 'B';
        while (!q.empty())
        {
            Cell cur = q.front();
            q.pop();
            int mines = getMines(board, cur.x, cur.y);
            if (mines > 0)
            {
                board[cur.x][cur.y] = '0' + mines;
                continue;
            }
            for (auto [dx, dy] : dirs)
            {
                int x = cur.x + dx, y = cur.y + dy;
                if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E')
                {
                    q.push({x, y});
                    board[x][y] = 'B';
                }
            }
        }
        return board;
    }
};
// @lc code=end
